//
//  StatusPictureView.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/14.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
import SDWebImage

//可重用 cell标示符
private let statusPictureViewCellID = "statusPictureViewCellID"

//选中通知
let GFStatusCellSelectPictureNotification = "GFStatusCellSelectPictureNotification"
//通知消息
let GFStatusSelectPictureURLKey = "GFStatusSelectPictureURLKey"
let GFStatusSelectPictureIndexKey = "GFStatusSelectPictureIndexKey"

class StatusPictureView: UICollectionView {
    
    var status:Status?{
        didSet{
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcIewSize()
    }
    
    //计算视图大小
    private func calcIewSize() -> CGSize {
        
        let itemeSize = CGSize(width: 90, height: 90)
        let magin: CGFloat = 10
        let RowCount = 3
        pictureLayout.itemSize = itemeSize
        
        //根据图片设置数量并计算大小
        let count = status?.picTureURLs?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
         //key就是一个完整的url字符串
        let key = status?.picTureURLs![0].absoluteString
             //image可能不存在
       let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
           
            var size = CGSize(width: 150, height: 120)
            if image != nil {
               size = image.size
            }
            //设置宽度和高度
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            pictureLayout.itemSize = size
        }
        
        if count == 4 {
            let w = itemeSize.width * 2 + magin
            return CGSize(width: w, height: w)
        }
        //如果图片数量不等于以上几个
        let row = (count - 1) / RowCount + 1
        let w = itemeSize.width * CGFloat(row) + magin * CGFloat(RowCount - 1)
        let h = itemeSize.height * CGFloat(row) + magin * CGFloat(RowCount - 1)
        return CGSize(width: w, height: h)
    }
    
    //图片布局
    private let pictureLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        backgroundColor = UIColor.darkGrayColor()
        
        //注册可从用cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: statusPictureViewCellID)
        
        //设置数据源
        self.dataSource = self
        self.delegate = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension StatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate {
    //选中单元格代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        
//        //缩略图cell的位置  测试代码
//        let v = UIView()
//        v.backgroundColor = UIColor.redColor()
//        v.frame = cellForScreenFrame(indexPath)
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
    
        //通知中心
        NSNotificationCenter.defaultCenter().postNotificationName(GFStatusCellSelectPictureNotification,
            object: self,
            userInfo: [GFStatusSelectPictureURLKey: status!.largePictrueURL!,
                GFStatusSelectPictureIndexKey: indexPath])
        
    }
    //计算cell在屏幕上的位置
    func cellScreenFrame(indexPath:NSIndexPath) ->CGRect {
        
        let cell = self.cellForItemAtIndexPath(indexPath)!
        
        return convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)

    }
    
    //缩略图放大后的位置
    func cellForScreenFrame(indexPath:NSIndexPath) ->CGRect {
    
        //1拿到缩略图
        let key = status!.picTureURLs![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        //2根据缩略图计算比例
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        let height = screenSize.width * scale
        
        //3考虑长短图
        var y: CGFloat = 0
        if height < screenSize.height {
            y = (screenSize.height - height) * 0.5
        }
        return CGRect(x: 0, y: y, width: screenSize.width, height: height)
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return status?.picTureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
     cell.backgroundColor = UIColor.redColor()
     cell.imageURL = status?.picTureURLs![indexPath.item]
     return cell
        
        }
    }
class StatusPictureViewCell: UICollectionViewCell {
    
    var imageURL:NSURL? {
        didSet{
            iconView.sd_setImageWithURL(imageURL!)
            
            //根据url判断是否是动图gif
            gifImageView.hidden = ((imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif")
        }
    }
    
    //构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(iconView)
        //添加gif
        iconView.addSubview(gifImageView)
        
        //自动布局
        iconView.ff_Fill(contentView)
        gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
  
    }
    
    //懒加载控件
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
        
    }()
    //懒加载gif图标
    private lazy var gifImageView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
}
